package com.linhdoha.ui 
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	/**
	 * ...
	 * @author Linhdoha
	 */
	public class BaseItem extends Sprite
	{
		private var _icon:DisplayObject;
		
		private var _bgSkin:String = "_bgSkin";
		
		private var bg:Sprite;
		private var _width:Number=50;
		private var _height:Number=50;
		private var _isSelected:Boolean = false;
		private var _data:Object;
		
		public function BaseItem() 
		{
			bg = new Sprite();
			bg.graphics.beginFill(0xFFFFFF, 1.0);
			bg.graphics.drawRect(0, 0, _width, _height);
			bg.graphics.endFill();
			addEventListener(MouseEvent.MOUSE_OVER, onOver);
			addEventListener(MouseEvent.MOUSE_OUT, onOut);
			addChild(bg);
		}
		
		private function onOut(e:MouseEvent):void 
		{
			_isSelected = false;
			redraw();
		}
		
		private function onOver(e:MouseEvent):void 
		{
			_isSelected = true;
			redraw();
		}
		
		private function redraw():void {
			if (_isSelected) bg.graphics.beginFill(0x0098FF, 0.2) else bg.graphics.beginFill(0xFFFFFF, 1.0);
			bg.graphics.drawRect(0, 0, _width, _height);
			bg.graphics.endFill();
			if (_icon) {
				if (_icon.width > _icon.height) {
					_icon.width = _width;
					_icon.scaleY = _icon.scaleX;
				} else {
					_icon.height = _height;
					_icon.scaleX = _icon.scaleY;
				}
				_icon.x = (_width - _icon.width) / 2;
				_icon.y = (_height - _icon.height) / 2;
			}
			
		}
		
		public function setIcon(i:DisplayObject):void {
			_icon = i;
			_icon.addEventListener(Event.ADDED, onAdded);
			addChild(_icon);
		}
		
		private function onAdded(e:Event):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, onAdded);
			redraw();
		}
		
		override public function get width():Number { return _width; }
		
		override public function set width(value:Number):void 
		{
			_width = value;
			redraw();
		}
		
		override public function get height():Number { return _height; }
		
		override public function set height(value:Number):void 
		{
			_height = value;
			redraw();
		}
		
		public function get data():Object { return _data; }
		
		public function set data(value:Object):void 
		{
			_data = value;
			redraw();
		}
		
		public function setBgSkin(name:String):void {
			_bgSkin = name;
			redraw();
		}
	}

}